package com.bjf.util;

import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import com.bjf.common.ComCons;
import com.bjf.common.Module;
import com.bjf.common.Rescode;
import com.bjf.exception.BJFException;

public class SQLParser {

	private final static Pattern p = Pattern.compile("(?idmsux)select|from|where");
	private final static Pattern p1 = Pattern.compile("(?idmsux)order|group");

	/**
	 * parse select param
	 *
	 * @param input
	 * @return
	 */
	public static HashMap parse(String input)throws BJFException {
		try{
		StringTokenizer st = new StringTokenizer(input);
		HashMap map = new HashMap();
		String param = null;
		String preParam = null;
		/** ( flag. */
		boolean flag = true;
		/** ' flag. */
		boolean flag1 = true;
		/** order by group by flag. */
		boolean orderGroup = false;
		StringBuffer buffer = null;
		while (st.hasMoreTokens()) {
			param = st.nextToken();
			if (param.startsWith("(")) {
				flag = false;
			} else if (param.endsWith(")")) {
				flag = true;
			} else if (param.startsWith("'")||param.endsWith("'")) {
				flag1 = !flag1;
			}
			if (flag && flag1) {
				if (p.matcher(param).matches()) {
					buffer = new StringBuffer();
					map.put(param, buffer);
				} else {
					if (p1.matcher(param).matches()) {
						orderGroup = true;
						preParam = param;
					} else {
						if (orderGroup) {
							if (param.equalsIgnoreCase("by")) {
								orderGroup = false;
								buffer = new StringBuffer();
								map.put(preParam + ComCons.SPACE + param, buffer);
							} else {
								buffer.append(preParam + ComCons.SPACE);
								buffer.append(param + ComCons.SPACE);
							}
						} else {
							buffer.append(param + ComCons.SPACE);
						}
					}
				}
			} else {
				buffer.append(param + ComCons.SPACE);
				/* shen_antonio .*/
				flag = flag1 = true;
			}
		}
		return map;
		}catch (Exception ex) {
			throw new BJFException(Module.SYSTEM_MODULE,
					Rescode.SQLPARSER_PARSE_FAIL, ex);
		}
	}
/*
	public static void main(String[] args){
		String sql = "select * from table where tal = '   ' and efwei = 'fweij fwje'";
		HashMap map = parse(sql);
		Iterator it = map.keySet().iterator();
		String key,value;
		while(it.hasNext()){
			key = it.next().toString();
			value = map.get(key).toString();
			System.out.println(key + " : " + value);
		}
	}
*/
}
